import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

// 创建 axios 实例
const service: AxiosInstance = axios.create({
  baseURL: '/api', // API 的基础URL
  timeout: 15000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 判断当前路由或 pinia 状态
    const path = window.location.pathname
    let token = ''
    if (path.startsWith('/user')) {
      token = localStorage.getItem('token') || ''
    } else if (path.startsWith('/rider')) {
      token = localStorage.getItem('rider_token') || ''
    } else if (path.startsWith('/merchant')) {
      token = localStorage.getItem('merchant_token') || ''
    } else if (path.startsWith('/admin')) {
      token = localStorage.getItem('admin_token') || ''
    }
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  (error) => Promise.reject(error)
)
// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    
    // 根据后端约定的状态码判断请求是否成功
    if (data.code === 0) {
      return data
    }
    
    // 处理特定的错误码
    switch (data.code) {
      case 401: // 未授权
        ElMessage.error('请先登录')
        localStorage.removeItem('token')
        router.push('/login')
        break
      case 403: // 权限不足
        ElMessage.error('权限不足')
        break
      case 500: // 服务器错误
        ElMessage.error('服务器错误')
        break
      default:
        ElMessage.error(data.message || '请求失败')
    }
    
    return Promise.reject(new Error(data.message || '请求失败'))
  },
  (error) => {
    // 处理 HTTP 错误状态
    if (error.response) {
      switch (error.response.status) {
        case 401:
          ElMessage.error('请先登录')
          localStorage.removeItem('token')
          router.push('/login')
          break
        case 403:
          ElMessage.error('权限不足')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器错误')
          break
        default:
          ElMessage.error('网络错误')
      }
    } else {
      ElMessage.error('网络连接失败')
    }
    return Promise.reject(error)
  }
)

// 封装 GET 请求
export function get<T>(url: string, params?: any): Promise<T> {
  return service.get(url, { params })
}

// 封装 POST 请求
export function post<T>(url: string, data?: any): Promise<T> {
  return service.post(url, data)
}

// 封装 PUT 请求
export function put<T>(url: string, data?: any): Promise<T> {
  return service.put(url, data)
}

// 封装 DELETE 请求
export function del<T>(url: string): Promise<T> {
  return service.delete(url)
}

export default service 